<?php

namespace Tools\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        die;
        ini_set("memory_limit","-1");
        ob_end_clean();
        echo str_pad('',1024);
        $t1 = microtime(true);
        $wb_nb_userM = M("wb_nb_user",null,HEED_CFG);
        $third_login_userM = M("third_login_user_copy",null,HEED_CFG);
        $cityM = M("city",null,HEED_CFG);
        $city_usersM = M("city_users",null,HEED_CFG);

        $restaurant_visitM = M("restaurant_visit",null,HEED_CFG);
        $share_appM = M("share_app",null,HEED_CFG);
        $photoM = M("photo",null,HEED_CFG);

        $collectM = M("collect",null,HEED_CFG);

        //主库
        $u_user_baseM = M("u_user_base", null, HE_CFG);
        $u_user_weiboM = M("u_user_weibo", null, HE_CFG);
        $u_user_weixinM = M("u_user_weixin", null, HE_CFG);

        $e_eventsM = M("e_events", null, HE_CFG);
        $e_events_joinM = M("e_events_join", null, HE_CFG);

        $articleM = M("article", null, HE_CFG);

        $comment_aM = M("comment_1", null, HE_CFG);
        $comment_bM = M("comment_2", null, HE_CFG);

        $praise_logM = M("praise_log", null, HE_CFG);

        //合用户
//        e("strat 合用户");
//        $u_user_baseM->execute("INSERT INTO star_core.u_user_base (uid,nickname,sex,regFrom,regTime,regIP,userPWD,point,realName,bindPhone,email,lastLoginTime,lastLoginIP,location,birthday,level)
//                SELECT uid,uname,sex,source,regdate,regip,passwd,coin,realName,mobile,email,lastlogintime,lastloginip,location,from_unixtime(birthday,'%Y-%m-%d') as birthday,0 FROM kannb.wb_nb_user");
//        $u_user_weiboM->execute("INSERT INTO star_core.u_user_weibo (uid,wid,wname,access_token,expire) SELECT uid,id,`name`,access_token,expire FROM kannb.wb_nb_user");
//        e("end 合用户");
//        //合活动
//        e("strat 活动");
//        $u_user_baseM->execute("INSERT INTO star_core.e_events (id,title,contentType,model,imgList,content,addTime,showTime,startTime,endTime,applyStartTime,applyEndTime,price,point,places,location,hot,sponsor,showListTime)
//                SELECT id,`name`,CASE WHEN type = 'MEISHI' THEN 1  WHEN type = 'MOVIE' THEN 14 WHEN type = 'PARTY' THEN 1 WHEN type = 'THEATRE' THEN 14 WHEN type = 'OUTDOOR' THEN 15 WHEN type = 'TRAVEL' THEN 2 WHEN type = 'TRY' THEN 1 WHEN type = 'SHOW' THEN 14 WHEN type = 'TRADE' THEN 13 END,'random',image,content,unix_timestamp(),sign_stime,UNIX_TIMESTAMP(concat(sdate,' ',stime)),UNIX_TIMESTAMP(concat(sdate,' ',etime)),sign_stime,sign_etime,fee,gold,amount,address,`view`,uid,FROM_UNIXTIME(sign_stime,'%Y-%m-%d') FROM kannb.city where kannb.city.show = 1");
//        $e_events_joinM->execute("INSERT INTO star_core.e_events_join (id,eid,uid,addTime,status,phone,realName,mark,`from`,cango,`select`)
//                SELECT `id`,cid,uid,createtime,cango,phone,`name`,saywhat,`from`,cango,`select` FROM kannb.city_users ");
//        $e_events_joinM->execute("UPDATE star_core.e_events_join SET status = 2 WHERE cango = 1");
//        $e_events_joinM->execute("UPDATE star_core.e_events_join SET status = 3 WHERE cango = 0");
//        $e_events_joinM->execute("UPDATE star_core.e_events_join SET status = 4 WHERE cango = 2");
//        e("end 活动");
        //合文章
        //PC文章
//        $articleM->execute("INSERT INTO star_core.article (uid,title,viewNum,contentType,shopID,content,listPic,audit,addTime,point,score,oldid,private,oldtype,channel)
//                SELECT uid,title,`view`,classify,restaurant,content,image,2,createtime,coin,reclevel,id,3,'restaurant_visit',1 FROM kannb.restaurant_visit WHERE kannb.restaurant_visit.isDraft = 0");
         /*** APP的文章不要合了
        $res = $share_appM->select();
        foreach ($res as $val){
            $data = array();
            $content = '';
            if($val['images']) {
                $listimg = $photoM->where(array('id'=>array('in', $val['images'])))->select();
                $desc = json_decode($val['desc'], true);
                foreach ($listimg as $k=>$v){
                    $content .= "<p><img src=\"".$v['url']."\"/></p>";
                    if($desc[$v['id']]) $content .= "<p>".$desc[$v['id']]."</p>";
                }
            }
            $content .= $val['content'];
            $data['uid'] = $val['uid'];
            $data['title'] = $val['title'];
            $data['viewNum'] = $val['view'];
            $data['shopID'] = $val['restaurant'];
            $data['content'] = $content;
            $data['listPic'] = $val['image'];
            $data['audit'] = 2;
            $data['addTime'] = $val['createtime'];
            $data['point'] = $val['coin'];
            $data['score'] = $val['score'];
            $data['uid'] = $val['uid'];
            $data['oldid'] = $val['id'];
            $data['oldtype'] = 'share';
              $data['channel'] = 1;
            $data['private'] = $val['private'] == 0 ? 3 : $val['private'];
            $articleM->add($data);
        }
        ***/

        //合 评论
       // 活动
        /****$comment_aM->execute("INSERT INTO star_core.comment_1 (parentID,objType,objID,content,uid,addTime,oldtype)
                SELECT parent,1,objid,comment,uid,createtime,type FROM kannb.comments where kannb.comments.type = 'restaurant_visit' OR kannb.comments.type = 'share' ");****/
        
//        $comment_aM->execute("INSERT INTO star_core.comment_1 (id,parentID,objType,objID,content,uid,addTime,oldtype)
//                SELECT id,parent,1,objid,comment,uid,createtime,type FROM kannb.comments where kannb.comments.type = 'restaurant_visit' ");
//
//        $comment_bM->execute("INSERT INTO star_core.comment_2 (id,parentID,objType,objID,content,uid,addTime)
//                SELECT id,parent,2,objid,comment,uid,createtime FROM kannb.comments where kannb.comments.type = 'city'");
//
//        $praise_logM->execute("INSERT INTO star_core.praise_log (objID,objType,uid,addTime)
//                SELECT objid,1,uid,createtime FROM kannb.collect where kannb.collect.type = 'restaurant_visit'");

        //文章ID 修改对应评论ID
//        $res = $articleM->field('id,content,listPic,oldid,oldtype')->select();
//        foreach ($res as $val){
//            $articleM->where("id = '{$val['id']}'")->save( array("content"=>htmlspecialchars_decode($val['content'])) );
//            if (preg_match_all('/<img[^>]+src=.(http[s]?:\/\/[^\'"]*)[^>]*>/', htmlspecialchars_decode($val['content']), $matches) && $val['listPic'] == '') {
//                foreach ($matches[1] as $vl){
//                    if(!strpos($vl,'.gif')){
//                        $articleM->where("id = '{$val['id']}'")->save( array("listPic"=>$vl) );
//                    }
//                }
//            }
//            $comment_aM->where("objID = '{$val['oldid']}' AND oldtype = '{$val['oldtype']}'")->save( array("objID"=>$val['id']) );
            /****$comment_aM->where("parentID = '{$val['oldid']}' AND oldtype = '{$val['oldtype']}'")->save( array("objID"=>$val['id']) );****/
//            $praise_logM->where("objID = '{$val['oldid']}' AND objType = 1")->save( array("objID"=>$val['id']) );
//        }

//        $articleM->execute(" UPDATE article,u_user_base SET article.nickname = u_user_base.nickname where article.uid = u_user_base.uid");
//        $comment_aM->execute(" UPDATE comment_1,u_user_base SET comment_1.nickname = u_user_base.nickname where comment_1.uid = u_user_base.uid");
//        $comment_bM->execute(" UPDATE comment_2,u_user_base SET comment_2.nickname = u_user_base.nickname where comment_2.uid = u_user_base.uid");
//        $praise_logM->execute(" UPDATE praise_log,u_user_base SET praise_log.nickname = u_user_base.nickname where praise_log.uid = u_user_base.uid");
//        $e_events_joinM->execute(" UPDATE e_events_join,u_user_base SET e_events_join.nickname = u_user_base.nickname where e_events_join.uid = u_user_base.uid");
//
//        $articleM->execute(" UPDATE article,(SELECT count(1) as ct,objID FROM comment_1 GROUP BY objID) as b SET article.commentNum = b.ct where article.id = b.objID");
//        $articleM->execute(" UPDATE e_events,(SELECT count(1) as ct,objID FROM comment_2 GROUP BY objID) as b SET e_events.commentNum = b.ct where e_events.id = b.objID");
//        $articleM->execute(" UPDATE e_events,(SELECT count(1) as ct,eid FROM e_events_join GROUP BY eid) as b SET e_events.applyCount = b.ct where e_events.id = b.eid");

        //第三方 登陆处理
        //删除 重复数据
//        $third_quchong = "select count(token) as count from third_login_user_copy group by token having count >1 order by count desc";
//        $third_quchong_res = $third_login_userM->query($third_quchong);
//        if($third_quchong_res){
//            for($i = 0; $i<$third_quchong_res[0]['count'];$i++){
//                $third_login_userM->execute("delete from third_login_user_copy where third in (select third from (select min(third) as third,count(token) as count from third_login_user_copy group by token having count >1 order by count desc) as tab )");
//            }
//        }
        e("start 微信");
        $res = $third_login_userM->query("select uid,token,unionid from third_login_user_copy");
        foreach ($res as $val){
            e("微信: ".$val['id']." end");
            $data = array();
            if(strripos($val['token'],'o94') !== false){
                $data = array('uid'=>$val['uid'],'WX2_openID'=>$val['token'], 'WX_unionID'=>$val['unionid']);
            }elseif ( strripos($val['token'],'oNO') !== false ){
                $data = array('uid'=>$val['uid'],'WX2_openID'=>$val['token'], 'WX_unionID'=>$val['unionid']);
            }elseif ( strripos($val['token'],'op0') !== false ){
                $data = array('uid'=>$val['uid'],'app_openID'=>$val['token'], 'WX_unionID'=>$val['unionid']);
            }
            if($u_user_weixinM->query("select * from u_user_weixin where uid = '{$val['uid']}'")){
                unset($data['uid']);
                $u_user_weixinM->where("uid = '{$val['uid']}'")->save($data);
            }else if($u_user_weixinM->query("select * from u_user_weixin where WX_unionID = '{$val['unionid']}'")){
                unset($data['uid']);
                $u_user_weixinM->where("WX_unionID = '{$val['unionid']}'")->save($data);
            }else{
                if($data){
                    $u_user_weixinM->add($data);
                }
            }
        }







        /*
        for($i = 0; $i<1000; $i++){
            $users = $wb_nb_userM->limit($i*100,100)->select();
            if($users){
                foreach ($users as $val){
                    $source = 1;
                    switch ($val['source']){
                        case 1: $source = 3;break;
                        case 2: $source = 2;break;
                        case 3: if($val['ufrom'] ==3)$source = 1;else $source = 5;break;
                    }
                    $province = self::getRegionByName($val['location']);

                    $birthday = $val['birthday'] ? date("Y-m-d", $val['birthday']) : '';
                    $sql = "INSERT INTO u_user_base (uid,nickname,sex,regFrom,regTime,regIP,userPWD,point,realName,bindPhone,email,lastLoginTime,lastLoginIP,province,city,district,birthday)
                            VALUES ('{$val['uid']}','{$val['uname']}','{$val['sex']}','{$source}','{$val['regdate']}','{$val['regip']}','{$val['passwd']}','{$val['gold']}','{$val['realName']}','{$val['mobile']}','{$val['email']}','{$val['lastlogintime']}','{$val['lastloginip']}','{$province['province']}','{$province['city']}','{$province['district']}','{$birthday}')";
                    $u_user_baseM->execute($sql);


                    $sqlweibo = "INSERT INTO u_user_weibo (uid,wid,wname,access_token,expire) VALUES ('{$val['uid']}','{$val['id']}','{$val['name']}','{$val['access_token']}','{$val['expire']}')";
                    $u_user_weiboM->execute($sqlweibo);

                    echo "uid:".$val['uid']."uname:".$val['uname']."<br />\n\r";
                    flush();    //刷新输出缓冲
                    //sleep(1);
                    unset($val);
                }
                unset($users);
            }
        }
        */
        e("合完成");
        $t2 = microtime(true);
        echo '耗时'.round($t2-$t1,3).'秒';
        //print_r(C('REGION'));
        
        
        
        
        
        
        
        
        
        
        
        
        
    }


    public function getRegionByName($name)
    {
        $rid = $cid = $aid = 0;
        list($r, $c, $a) = explode('|',$name);
        if($r) $rid = self::getRegion($r);
        if($r && $c) $cid = self::getRegion($c, $rid);
        if($r && $c && $a) $aid = self::getRegion($a, $cid);

        return array('province'=>$rid, 'city'=> $cid, 'district'=>$aid);
    }

    public function getRegion($r, $c){
        $re = C("REGION");
        foreach ($re as $val){
            if($c) {
                if ($val[2] == $r && $c == $val[1]) {
                    return $val[0];
                    break;
                }
            }else{
                if ($val[2] == $r) {
                    return $val[0];
                    break;
                }
            }
        }

    }


    public function ajaxUpload(){
        $this->ajaxReturn(self::imageUpload('file',C('FILE_UPLOAD_DIR')));
    }


    /**
     * 上传图片
     * @param string $photo_field_nam,form中存放图片的字段名
     * @param string $rootPath 以站点根目录开始，以/开始,以/结尾
     * @return array(
     *      id,0表示出错，其他值表示正确
     *      msg，出错时为提示信息，图片存放路径
     * )
     */
    private function imageUpload($photo_field_name = 'photo',$rootPath = ''){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小 3*1024*1024 3M
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = '.'.$rootPath; // 设置附件上传根目录

        $return=array('id'=>0,'msg'=>'');
        // 上传单个文件
        $info = $upload->uploadOne($_FILES[$photo_field_name]);

        if(!$info) {// 上传错误提示错误信息
            $return['msg']=$upload->getError();
        }else{// 上传成功 获取上传文件信息

            $newMD5     = $info['md5'];
            $photoLib   = M('photo_lib',null,DB_MAIN_CFG);
            $existPhoto = $photoLib->where(array('md5'=>$newMD5))->find();
            $fullPath   = $rootPath.$info['savepath'].$info['savename'];
            if($existPhoto){
                @unlink ('./'.$fullPath);
                $existPhoto['ref'] +=1;
                $photoLib->save($existPhoto);
                $return= array('id'=>$existPhoto['id'],'msg'=>$existPhoto['path']);
            }else{
                $result=$photoLib->add(array('path'=>$fullPath,'md5'=>$newMD5,'ref'=>1));
                if($result!==false){
                    $return= array('id'=>$result,'msg'=>$fullPath);
                }
            }

        }
        return $return;
    }


    // base64图片上传
    public function base64upload() {
        $dataURL = $_POST['dataURL'];
        list($mime, $data) = explode(',', $dataURL);
        $blob = base64_decode($data);
        $mime_array = explode(';', $mime);
        $mime_array = $mime_array[0];
        $extName=explode('/', $mime_array);
        $extName = $extName[1];

        $rootPath=C('FILE_UPLOAD_DIR');
        $result = $this->UploadImage($blob,$rootPath,$extName);
        if ($result) {
            return print(json_encode(array('status' => 0, 'url' => $result)));
        }
        return print(json_encode(array('status' => 1)));
    }

    //图片上传
    private function UploadImage($blob, $direct,$extName='.jpg') {
        if($extName[0]!='.')
        {
            $extName ='.'.$extName;
        }

        $direct.=date('Y-m-d/');
        $name=date('His_').rand(1,1000).$extName;
        //创建目录
        $dirpath=WEB_ROOT.$direct;

        if(!is_dir($dirpath)){
            if(!mkdir($dirpath, 0777, true)){
                return "";
            }
        }

        file_put_contents(WEB_ROOT.$direct.$name, $blob);//返回的是字节数printr(a);
        $newMD5=md5_file(WEB_ROOT.$direct.$name);
        $photoLib   = M('photo_lib',null);
        $existPhoto = $photoLib->where(array('md5'=>$newMD5))->find();

        $fullPath   = $direct.$name;// $rootPath.$info['savepath'].$info['savename'];

        if($existPhoto){
            @unlink (WEB_ROOT.$direct.$name);
            $existPhoto['ref'] += 1;
            $photoLib->save($existPhoto);
            $return= $existPhoto['path'];
        }else{
            $result=$photoLib->add(array('path'=>$fullPath,'md5'=>$newMD5,'ref'=>1));
            if($result!==false){
                $return= $fullPath;
            }
        }
        return $return;
    }





}

function e($str){
    echo $str."\n\r";
    flush();
}